#include "server.h"
#include <fstream>
Server::Server()
{
    sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (sock_fd == -1)
    {
        cout << "创建套接字失败" << endl;
        return;
    }
    int on = 1;
    int ret = setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
    if (ret < 0)
    {
        cout << "设置地址复用失败" << endl;
    }
}

void Server::Connect_the_client() //连接客户端
{

    int retval;
    struct sockaddr_in addr;
    addr.sin_family = AF_INET; // IPV4
   
    addr.sin_port = htons(10010); //端口号
    addr.sin_addr.s_addr=inet_addr("127.0.0.1");
    
    retval = bind(sock_fd, (struct sockaddr *)&addr, sizeof(addr));
    if (retval == -1)
    {
        cout << "绑定ip地址与端口失败" << endl;
        return ;
    }
    retval = listen(sock_fd, 100);
    if (retval == -1)
    {
        cout << "设置网络容量失败" << endl;
        return;
    }
}

void *client_thread(void *arg)
{
    ssize_t recv_ret;
    Client *l = (Client *)arg;
    while (1)
    {
       
        Menu m;
        unsigned int i;
        recv(l->client_id, &i, sizeof(i), 0);
        for (unsigned int j; j < i; j++)
        {
            recv_ret = recv(l->client_id, &m, sizeof(m), 0);
            if (recv_ret == -1)
            {

                cout << "客户端连接断开" << endl;
                break;
            }
            else if (recv_ret == -1)
            {

                cout << "读取客户端异常" << endl;
                return (void *)-1;
            }
            l->myMenu.push_back(new Menu(m.names, m.bmp_path, m.prices, m.counts));
        }
        for (unsigned int i = 0; i < l->myMenu.size(); i++)
        {
            cout <<"菜品名字："<< l->myMenu[i]->names << endl;
            cout <<"菜品价格："<< l->myMenu[i]->prices <<"元"<< endl;
            cout <<"购买菜品份量："<<l->myMenu[i]->counts << endl;
            
            ofstream outfile;
            outfile.open("output.txt"); 
            outfile<<"菜品"<<l->myMenu[i]->names<<endl;
            outfile<<"价格"<<l->myMenu[i]->prices<<endl;
            outfile<<"数量"<<l->myMenu[i]->counts<<endl;
            outfile.close();
            
        }
       
    }

    return NULL;
}

void Server::WaitConnect()
{
    int client_fd;
    struct sockaddr_in recv_addr;      //定义ipv4的结构体
    socklen_t len = sizeof(recv_addr); //规定接受的地址长度
  while(1)
    {printf("等待客户端连接..\n");

        client_fd = accept(sock_fd, (struct sockaddr *)&recv_addr, &len);
        if (client_fd == -1)
        {
            cout << "服务器：客户端连接失败" << endl;
            return;
        }
        cout << "连接成功" << endl;
        Client *c = new Client;
        c->client_id = client_fd;
        //cout<<c->client_id<<endl;
        pthread_create(&c->pid, NULL, client_thread, c);
    }
    
}

Server::~Server()
{
    for (unsigned int i = 0; i < myclient.size(); i++)
    {
        close(myclient[i]->client_id);
        pthread_join(myclient[i]->pid, NULL);
    }
}
int main()
{
    Server s;
    s.Connect_the_client();
    s.WaitConnect();
}